package org.frame.gateway.config;

import org.frame.common.core.constants.Constants;
import org.frame.common.core.entity.TokenUser;
import org.frame.gateway.token.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;

import lombok.extern.slf4j.Slf4j;
import reactor.core.publisher.Mono;

@Slf4j
@Configuration
public class MyGlobalFilter implements GlobalFilter, Ordered{
	
	@Autowired
	private Urls urls;
	@Autowired
	private TokenService tokenService;
	
	@Override
	public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
		ServerHttpRequest request = exchange.getRequest();
		ServerHttpResponse response = exchange.getResponse();
		String path = request.getPath().toString();
		log.info("进入路由过滤器，请求类型：{}，path：{}", request.getMethod(), path);
		log.info("白名单：{}", urls.getWhitelist());
		boolean contains = urls.getWhitelist().contains(path);
		if(contains) {
			log.info("请求地址：{} 放行", path);
			return chain.filter(exchange);
		}
		try {
			HttpHeaders headers = response.getHeaders();
			log.info("请求地址：{} 不在白名单中，校验token", path);
			TokenUser tokenUser = tokenService.getTokenUser(request);
			if(tokenUser != null) {
				//向headers中放token，记得build
				request = request.mutate().header(Constants.USER_TOKEN_HEADER, tokenUser.getToken()).build();
		        //将现在的request 变成 change对象 
		        exchange = exchange.mutate().request(request).build();
				tokenService.verifyToken(tokenUser);
			}else {
				headers.add("Content-Type", "application/json");
				response.setStatusCode(HttpStatus.UNAUTHORIZED);
				return response.writeWith(Mono.empty());
			}
		} catch (Exception e) {
			log.error("路由异常", e);
		}
		return chain.filter(exchange);
	}

	@Override
	public int getOrder() {
		return 0;
	}
	
	

}
